package com.gopay.common.util;

import java.util.Calendar;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SendMail {
	private static Logger logger = LoggerFactory.getLogger(SendMail.class);

	@SuppressWarnings("static-access")
	public static void sendMessage(String smtpHost, String from, String userName, String fromUserPassword, String to,
			String subject, String messageText, String messageType, List cc, List files, List fileNames)
					throws MessagingException {
		// 第一步：配置javax.mail.Session对象
		logger.error("为" + smtpHost + "配置mail session对象");

		Properties props = new Properties();
		props.put("mail.smtp.host", smtpHost);
		//props.put("mail.smtp.starttls.enable", "true");// 使用 STARTTLS安全连接
		// props.put("mail.smtp.port", "25"); //google使用465或587端口
		props.put("mail.smtp.auth", "true"); // 使用验证
		// props.put("mail.debug", "true");
		Session mailSession = Session.getInstance(props, new MyAuthenticator(from, fromUserPassword));

		// 第二步：编写消息
		logger.error("编写消息from——to:" + from + "——" + to);

		InternetAddress fromAddress = new InternetAddress(from);
		InternetAddress toAddress = new InternetAddress(to);
		// InternetAddress ccAddress = new InternetAddress(cc);

		MimeMessage message = new MimeMessage(mailSession);

		message.setFrom(fromAddress);
		message.addRecipient(RecipientType.TO, toAddress);
		// message.addRecipient(RecipientType.CC, ccAddress);
		if (cc != null) {
			message.setRecipients(RecipientType.CC, listToAddressArray(cc));
		}

		message.setSentDate(Calendar.getInstance().getTime());
		message.setSubject(subject);
		// message.setContent(messageText, messageType);

		// 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
		Multipart multipart = new MimeMultipart();

		// 设置邮件的文本内容
		BodyPart contentPart = new MimeBodyPart();
		contentPart.setText(messageText);
		multipart.addBodyPart(contentPart);

		for (int i = 0; i < files.size(); i++) {
			String file = (String) files.get(i);
			String fileName = (String) fileNames.get(i);
			// 添加附件
			BodyPart messageBodyPart = new MimeBodyPart();
			DataSource source = new FileDataSource(file);
			// 添加附件的内容
			messageBodyPart.setDataHandler(new DataHandler(source));
			// 添加附件的标题
			messageBodyPart.setFileName(fileName);
			multipart.addBodyPart(messageBodyPart);
		}

		// 将multipart对象放到message中
		message.setContent(multipart);
		// 保存邮件
		message.saveChanges();

		//忽略信任证书验证
		try {
			HostnameVerifier hv = new HostnameVerifier() {
				@Override
                public boolean verify(String urlHostName, SSLSession session) {
					logger.error("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost());
					return true;
				}
			};
			trustAllHttpsCertificates();

			HttpsURLConnection.setDefaultHostnameVerifier(hv);
			logger.info("---------before send--------");
			// 第三步：发送消息
			Transport transport = mailSession.getTransport("smtp");
			logger.info("---------before connect--------");
			transport.connect(smtpHost, userName, fromUserPassword);
			logger.info("---------after connect--------");
			transport.send(message, message.getAllRecipients());
			logger.info("SendMail yes");
		} catch (Exception e) {
			logger.error("SendMail fail" , e);
		}
	}

	/**
	 * 获取抄送人list
	 * 
	 * @param list
	 * @return
	 */
	private static Address[] listToAddressArray(List list) {
		Address[] array = new Address[list.size()];
		for (int i = 0; i < list.size(); i++) {
			String str = String.valueOf(list.get(i));
			Address address = null;
			try {
				address = new InternetAddress(str);
			} catch (AddressException e) {
				logger.error("SendMail getCcAddress error: ", e);
			}
			array[i] = address;
		}
		return array;

	}

	private static void trustAllHttpsCertificates() throws Exception {
		javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1];
		javax.net.ssl.TrustManager tm = new miTM();
		trustAllCerts[0] = tm;
		javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
		sc.init(null, trustAllCerts, null);
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	}

	static class miTM implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager {
		@Override
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			return null;
		}

		public boolean isServerTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		public boolean isClientTrusted(java.security.cert.X509Certificate[] certs) {
			return true;
		}

		@Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}

		@Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType)
				throws java.security.cert.CertificateException {
			return;
		}
	}

	// public static void main(String[] args) {
	// try {
	// List files = new ArrayList();
	// List names = new ArrayList();
	// List cc = new ArrayList();
	//
	// files.add("D://bis-cmbc.log.2015-12-21");
	// files.add("D://bis-cmbc.log.2015-12-22");
	// names.add("bis-cmbc.log.2015-12-21");
	// names.add("bis-cmbc.log.2015-12-22");
	// cc.add("lli_li1@hnair.com");
	// cc.add("zheng-xue@hnair.com");
	//
	// SendMail.sendMessage("smtp.qiye.163.com", "cieccpay@gopay.com.cn",
	// "cieccpay@gopay.com.cn", "gft_cieccpay",
	// "zhengxue2487@163.com", "nihao", "---------------wrwe-----------",
	// "text/html;charset=gb2312", cc,
	// files, names);
	// } catch (MessagingException e) {
	// // TODO Auto-generated catch block
	// e.printStackTrace();
	// }
	// }
}
